﻿using Core.Framework.Model.Common;
using Core.Middleware.WebSockets;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Core.ApiClient
{

    public class Startup
    {

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            CoreStartupHelper.Configuration = configuration;

        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {

            services.AddSwaggerService();

            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services
                .AddMvc(options => options.Filters.Add<ExceptionHandlerFilter>())
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddJsonOptions(o => o.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss");
            


            BuildServiceProvider
                    .ServiceCollection
                    .AddContextService()
                    .AddBusinessService()
                    .TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
        {


            app.RegisterServiceProvider();

            app.RegisterSwagger();

            lifetime.RegisterApplicationLifetime(app);

            app.RegisterTimerJobs();




            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();
            else
                app.UseHsts();

            

            // 启用Https
            app.UseHttpsRedirection();
            app.UseStaticFiles();


            // WS中间件
            app
                .UseWebSocketsMiddleware()
                .UseQueueLoop()
                .UseQueueMsgBackups();



            // 跨域
            app.UseCors(builder => builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());

            app.UseMvc();

        }
    }
}
